<?php
/**
 * Created by PhpStorm.
 * User: suruixiang
 * Date: 2017/10/12
 * Time: 下午5:01
 */
namespace app\index\model;

use think\Model;
use think\Config;
use think\Session;

class Channel extends Model
{
    private $course_info;
    /**
     * 根据单字段获取信息
     * @param $user_name
     * @param string $fields
     * @return object
     */
    public function getInfoByField($field_name, $field_value, $fields = '*')
    {
        return $this->where($field_name, $field_value)->field($fields)->find();
    }

    /**
     * 根据条件获取单条渠道信息
     * @param $where
     * @param string $fields
     * @return array|false|\PDOStatement|string|Model
     */
    public function getInfoByWhere($where, $fields = '*')
    {
        return $this->where($where)->field($fields)->find();
    }
    /**
     * 获取渠道列表
     * @param array $where
     * @return array
     */
    public function getAllLists(array $where = [], $order = 'id desc', $page = true)
    {
        $coursesModel = new Courses();
        $userModel = new User();
        $coursesCategoryRelationModel = new CoursesCategoryRelation();
        $new_lists = [];
        $status = [
            1 => '正常',
            2 => '禁用'
        ];
        //课程名
        if ($where['courses_title']) {
            $courses_title = $where['courses_title'];
            unset($where['courses_title']);
            $course_ids = $coursesModel->getCourseIdByTitle($courses_title);
            if (!$course_ids) {
                return;
            }
            $where['course_id'] = ['in', $course_ids];
        }
        $lists = $page ? $this->where($where)->order($order)->paginate(Config::get('config.page_num'), false, ['query'=>request()->param()]) : $this->where($where)->order($order)->select();
        foreach ($lists as $li) {
            //渠道详情
            $channel_info['id'] = $li->id;
            $channel_info['course_id'] = $li->course_id;
            $channel_info['user_id'] = $li->user_id;
            $channel_info['create_time'] = $li->create_time;
            $channel_info['total_earnings'] = $li->total_earnings;
            $channel_info['total_visit'] = $li->total_visit;
            $channel_info['status'] = $status[$li->status];
            $channel_info['status_code'] = $li->status;
            //课程详情
            if (!$this->course_info[$li->course_id]) {
                $course_info = $coursesModel->getInfoByField('id', $li->course_id, 'title, cps_generalize_link, smallPicture, cps_banner, price, cps_generalize_earning');
                $this->course_info[$li->course_id] = [
                    'title'  => $course_info->title,
                    'cps_generalize_link' => $course_info->cps_generalize_link,
                    'banner' => $course_info->smallPicture ? $course_info->smallPicture : $course_info->cps_banner,
                    'price'  => $course_info->price,
                    'cps_generalize_earning' => $course_info->cps_generalize_earning,
                    'classify_name' => $coursesCategoryRelationModel->getCategoryByCourseId($li->course_id),
                    'h5_link' => Config::get('config.cz_h5_link') . $li->course_id
                ];
            }
            $channel_info['course_info'] = $this->course_info[$li->course_id];
            //发布人详情
            $user_info = $userModel->getInfoByField('id', $li->user_id, 'user_name');
            $channel_info['user_info'] = [
                'user_name' => $user_info->user_name,
            ];
            $channel_info['channel_url'] = request()->domain() . "/api/skip?channel_id={$li->id}";
            $new_lists[] = $channel_info;
            unset($channel_info);
        }
        if ($page)
            return [
                'lists' => $new_lists,
                'page'  => $lists->render()
            ];
        else
            return $new_lists;
    }

    /**
     * 获取渠道统计数据
     * @param array $where
     * @return array
     */
    public function stats(array $where = [])
    {
        $retuen = [
            'total_num' => 0,
            'total_earnings' => 0,
            'total_visit'    => 0
        ];
        if ($where['courses_title']) {
            $coursesModel = new Courses();
            $courses_ids = $coursesModel->getCourseIdByTitle($where['courses_title']);
            if (!$courses_ids) {
                return $retuen;
            }
            unset($where['courses_title']);
            $where['course_id'] = ['in', $courses_ids];
            $data = $this->where($where)->field('count(`id`) as num, sum(`total_earnings`) as earnings, sum(`total_visit`) as visit')->find();
        } else {
            unset($where['courses_title']);
            $data = $this->where($where)->field('count(`id`) as num, sum(`total_earnings`) as earnings, sum(`total_visit`) as visit')->find();
        }
        $retuen['total_num'] = intval($data->num);
        $retuen['total_earnings'] = intval($data->earnings);
        $retuen['total_visit'] = intval($data->visit);
        return $retuen;
    }
    /**
     * 修改数据
     * @param array $where
     * @param array $save
     * @return int
     */
    public function updateData(array $where = [], array $save = [])
    {
        return $this->where($where)->update($save);
    }

    /**
     * 生成渠道
     * @param $course_id
     * @return int
     */
    public function createData($course_id)
    {
        return $this->insertGetId([
            'course_id' => $course_id,
            'user_id' => Session::get('cps_user_id'),
            'create_time' => time(),
        ]);
    }
}